package myJs.user.workflow

import myJs.Implicits._
import myJs.Utils._
import myJs.myPkg._
import myJs.myPkg.jquery._
import myJs.myPkg.topology._
import myJs.tool.Tool
import myJs.tool.Tool._
import myJs.user.soft.fileSelect.FileModal
import myJs.user.workflow.featureSelection._
import org.scalajs.dom._
import org.scalajs.dom.ext.Ajax
import scalatags.Text.all._

import scala.scalajs.js
import scala.scalajs.js.Dynamic.{global => g}
import scala.scalajs.js.JSConverters._
import scala.scalajs.js.{JSON, URIUtils}
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}
import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
import upickle.default._

/** Created by yz on 2019/4/25
  */
@JSExportTopLevel("ViewHtml")
object ViewHtml {

  var topology: Topology = _
  var selectNode: Boolean = _
  var dirObj: ujson.Obj = _

  @JSExport("init")
  def init = {

    val topologyOptions = TopologyOptions(
      hideRotateCP = true,
      hideSizeCP = true,
      disableScale = true,
      disableEmptyLine = true,
      autoAnchor = false,
      hideAnchor = false,
      rotateCursor = "pointer",
      hoverCursor = "pointer",
      disableDockLine = true,
      hideInput = true,
      anchorFillStyle = "red"
    )
    topology = Topology(
      parent = "topo-canvas",
      options = topologyOptions
    )

    val graphDataDict = getGraphData.toJDJAn
    topology.open(graphDataDict)

    dirObj = read[ujson.Obj](JSON.stringify(getDirMapStr.toJDJAn))

    getPenLines(topology).foreach { pen =>
      pen.locked = Lock.NoEvent
    }

    topology.lockPens(topology.find("dataFileNode").toPens, Lock.NoEvent)
    topology.lockPens(getPenNodes(topology), Lock.Readonly)

    registerEvent

  }

  def getPenLines(topology: Topology) = {
    val pens = topology.data.pens
    pens.filter { pen =>
      pen.`type` == PenType.Line
    }
  }

  def getPenNodes(topology: Topology) = {
    val pens = topology.data.pens
    pens.filter { pen =>
      pen.`type` == PenType.Node && pen.id != "dataFileNode"
    }
  }

  def getGraphData = {
    g.graphData
  }
  def getDirMapStr = {
    g.dirMap
  }

  def registerEvent = {
    topology.on(
      "node",
      (pen: MyPen) => {
        val node = pen.toPen.toNode

        setSelectNode(true)
        val nodeText = node.text
        val mapDir = dirObj(node.text).str
        val dir = if (mapDir != "") s"${mapDir}/${nodeText}" else nodeText
        window.open(s"${dir}")
      }
    )
  }

  def setSelectNode(b: Boolean) = {
    selectNode = b
  }

}
